<template>
  <el-select v-model="state.examType" placeholder="选择考试类型" size="large" class="margin10px" clearable>
    <el-option label="完全公开" value="1" />
    <el-option label="需要密码" value="2" />
  </el-select>

  <span class="margin10px">
    <el-date-picker v-model="state.startTime" type="date" placeholder="开始时间" size="large" />
  </span>
  <span class="margin10px">
    <el-date-picker v-model="state.endTime" type="date" placeholder="结束时间" size="large" />
  </span>

  <el-input v-model="state.examName" placeholder="考试名称" @blur="handleInput" @keyup.enter="handleInput"
    :prefix-icon="Search" size="large" class="margin10px" />
  <br>
  <el-button type="primary" class="margin10px" @click="gotoAddExam" size="large"
    style="width: 90px;">+&nbsp;添加</el-button>
  <br>
  <el-select class="margin10px" v-model="selectValue" clearable :placeholder="selectPlaceholder" size="large"
    v-if="state.selectedRows.length > 0" @change="handleSelectChange">
    <el-option label="启用" value="on" />
    <el-option label="禁用" value="off" />
    <el-option label="删除" value="delete" />
  </el-select>
  <el-table :data="formattedExamData" border style="width: 100%" header-background="#f2f3f4"
    @selection-change="handleSelectionChange" tooltip-effect="dark">
    <el-table-column type="selection" width="55" />
    <el-table-column label="考试名称">
      <template v-slot="scope">
        <router-link class="custom-link" :to="{ path: `/home/updateExam/${scope.row.examId}` }">{{ scope.row.examName
          }}</router-link>
      </template>
    </el-table-column>
    <el-table-column property="examType" label="考试类型" />
    <el-table-column property="examTime" label="考试时间" />
    <el-table-column property="totalScore" label="考试总分" />
    <el-table-column property="passScore" label="及格分数" />
    <el-table-column property="status" label="状态" />
  </el-table>
  <br>
  <!-- 分页查询 -->
  <div class="demo-pagination-block">
    <el-pagination v-model:current-page="state.pageNum" v-model:page-size="state.pageSize" :page-sizes="[5, 10, 15, 20]"
      :background="background" layout="total, sizes, prev, pager, next, jumper" :total="state.total"
      @size-change="handleSizeChange" @current-change="handleCurrentChange">
    </el-pagination>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, inject, watch } from 'vue';
import { Search } from '@element-plus/icons-vue';
import { ElMessage, ElNotification } from 'element-plus';
import { useRouter } from 'vue-router';
const router = useRouter()
// 动态更新 select 的 placeholder
const selectPlaceholder = ref('');
const selectValue = ref('');
import {
  getExamInfos,
  operationExam1,
  operationExam2,
  operationExam3
} from '@/api/examControl/ExamManage'
// 定义数据
const state = reactive({
  examData: [],
  pageNum: 1,
  pageSize: 10,
  total: 0,
  examName: '',
  examType: '',
  startTime: '',
  endTime: '',
  selectedRows: [],
});

// 计算属性：格式化考试数据
const formattedExamData = computed(() => {
  return state.examData.map(exam => ({
    ...exam,
    examTime: exam.startTime && exam.endTime
      ? `${exam.startTime} ~ ${exam.endTime}`
      : '不限时',
    examType: exam.type == 1 ? '完全公开' : '需要密码',
    status: exam.status == 1 ? '启用' : '禁用'
  }));
});

// 监听考试类型、开始时间和结束时间的变化
watch(() => [state.examType, state.startTime, state.endTime], () => {
  getExamInfo();
});

// 分页大小变化和当前页变化的事件处理函数
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  state.pageSize = val;
  getExamInfo();
};

const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  state.pageNum = val;
  getExamInfo();
};

// 获取试题列表
async function getExamInfo() {
  try {
    let {data} = await getExamInfos({
      examName: state.examName || null,
      examType: state.examType || null,
      startTime: state.startTime || null,
      endTime: state.endTime || null,
      pageNo: state.pageNum,
      pageSize: state.pageSize,
    })
    // 请求无法获取数据总数,发送一个请求获取前一万条数据，数据量当做total
    let res =  await getExamInfos({
      examName: state.examName || null,
      examType: state.examType || null,
      startTime: state.startTime || null,
      endTime: state.endTime || null,
      pageNo: 1,
      pageSize: 10000,
    });
    state.examData = data.data;

    state.total = res.data.data.length; // 更新总数
  } catch (error) {
    console.error('获取试题列表时出错:', error);
  }
}

// 输入框失去焦点或按下回车键时的事件处理函数
const handleInput = () => {
  getExamInfo();
};

const resetSelect = () => {
  selectPlaceholder.value = '';
};

// 处理选中行变化的函数
const handleSelectionChange = (selectedRows: any[]) => {
  state.selectedRows = selectedRows;
  console.dir(state.selectedRows);
  selectPlaceholder.value = `已选择${selectedRows.length}项`;
};

const handleSelectChange = async (value: string) => {
  const ids = state.selectedRows.map(row => row.examId).join(',');
  try {
    if (value == 'on') {
      await operationExam1(ids);
      ElNotification({
        title: '启用',
        message: '操作成功',
        type: 'success',
      });
    } else if (value == 'delete') {
      await operationExam3(ids);
      ElNotification({
        title: '删除',
        message: '操作成功',
        type: 'success',
      });
    } else {
      await operationExam2(ids);
      ElNotification({
        title: '禁用',
        message: '操作成功',
        type: 'success',
      });
    }
  } catch (error) {
    ElNotification({
      title: value == 'delete' ? '删除' : (value == 'on' ? '启用' : '禁用'),
      message: '操作失败',
      type: 'error',
    });
    console.error('请求出错:', error);
  } finally {
    selectValue.value = '';
    selectPlaceholder.value = '';
    getExamInfo();
  }
};



// 切换到添加考试组件
function gotoAddExam() {
  router.push({ path: `/home/addExam` });
}
// 组件挂载时获取试题列表
onMounted(() => {
  getExamInfo();
});
</script>

<style scoped lang="less">
.custom-link
{
  text-decoration: none;
  color: #448ef7;
  font-weight: 200;
  /* 自定义颜色 */
}

.custom-link:hover
{
  color: #2980b9;
  /* 悬停时的颜色 */
}

.margin10px
{
  padding: 5px 5px 5px 0;
  display: inline-block;
  margin: 5px 5px 5px 0;
  width: 220px
}
</style>
